#!/bin/bash

set -e

cd "$(dirname "$0")/.."
root="$PWD"

clone_repo() {
	local owner=$1
	local name=$2
	local sha=$3
	local path="$root/examples/$name"

	if [ -d "$path" ]; then
		pushd "$path" >/dev/null
		if [ "$(git rev-parse HEAD 2>/dev/null)" == "$sha" ]; then
			popd >/dev/null
			return
		else
			popd >/dev/null
			rm -rf "$path"
			echo "Updating $owner/$name to $sha"
		fi
	else
		echo "Cloning $owner/$name"
	fi

	mkdir -p "$path"
	pushd "$path" >/dev/null
	git init
	git remote add origin "https://github.com/$owner/$name"
	git pull --ff-only --depth 1 origin "$sha"
	popd >/dev/null
}

clone_repo desktop desktop 7c5111425cab9de911f82dd7e42f92d8f7927bb1
clone_repo reduxjs redux 936e134b827a2f8022d51f6a42942e935ee2a935
clone_repo microsoft vscode 4acf2d9fd883d247b903cc9c33221e18e39bffd8

known_failures="$(cat script/known-failures.txt)"

# shellcheck disable=SC2046
tree-sitter parse -q \
	'examples/**/*.ts' \
	'examples/**/*.tsx' \
	$(for failure in $known_failures; do echo "!${failure}"; done)

example_count=$(find examples -name '*.ts*' -or -name '*.tx' | wc -l)
failure_count=$(wc -w <<<"$known_failures")
success_count=$((example_count - failure_count))
success_percent=$(bc -l <<<"100*${success_count}/${example_count}")

printf \
	"Successfully parsed %d of %d example files (%.1f%%)\n" \
	"$success_count" "$example_count" "$success_percent"
